package cn.whx.hrm.service.impl;

import cn.whx.hrm.CourseClient;
import cn.whx.hrm.config.RabbitMQConfig;
import cn.whx.hrm.constant.AuthConstant;
import cn.whx.hrm.constant.GradeLevel;
import cn.whx.hrm.doc.CourseDoc;
import cn.whx.hrm.domain.*;
import cn.whx.hrm.dto.Dto;
import cn.whx.hrm.mapper.CourseDetailMapper;
import cn.whx.hrm.mapper.CourseMapper;
import cn.whx.hrm.mapper.CourseMarketMapper;
import cn.whx.hrm.mapper.CourseTypeMapper;
import cn.whx.hrm.query.CourseDocQuery;
import cn.whx.hrm.service.ICourseService;
import cn.whx.hrm.util.AjaxResult;
import cn.whx.hrm.util.ValidUtils;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author whx
 * @since 2021-06-21
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {
    @Autowired
    private CourseMarketMapper courseMarketMapper;
    @Autowired
    private CourseDetailMapper courseDetailMapper;
    @Autowired
    private CourseTypeMapper courseTypeMapper;
    @Autowired
    private CourseClient courseClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public AjaxResult save(Dto dto) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //存入redis里
        String key = AuthConstant.USER_INFO_KEY + authentication.getPrincipal();
        UserContextInfo userInfo = (UserContextInfo) redisTemplate.opsForValue().get(key);

        //检验课程等级
        Course course = dto.getCourse();
        Long gradeId = course.getGradeId();
        //查询后台对应的课程
        GradeLevel level = GradeLevel.byId(gradeId);
        //判断结果
        ValidUtils.assertNotNull(level,"基本信息课程不存在");
        //课程名字存到ccourse中
        course.setGradeName(level.getGradeName());
        course.setTenantName(userInfo.getTenantName());
        course.setUserName(userInfo.getUserName());
        course.setUserId(userInfo.getUserId());
        //保存课程信息
        super.insert(course);
        //保存基本信息
        CourseMarket courseMarket = dto.getCourseMarket();
        courseMarket.setId(course.getId());
        courseMarketMapper.insert(courseMarket);
        //保存详情信息
        CourseDetail courseDetail = dto.getCourseDetail();
        courseDetail.setId(course.getId());
        courseDetailMapper.insert(courseDetail);
        return AjaxResult.me();
    }





    //课程上线
    @Override
    public AjaxResult onLine(List<Long> ids) {

        AjaxResult add = AjaxResult.me();
        for (Long id: ids){
            //根据一个id查询课程
            Course course = super.selectById(id);
            CourseDoc courseDoc = courseToCourseDoc(course);
            add  = courseClient.add(courseDoc);
            //判断是否存到ES里面去了
            if (!add.isSuccess())
                throw new RuntimeException(add.getMessage());
            //修改数据库的状态
            course.setStatus(1);//1上线
            super.updateById(course);
            rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME_TOPIC,"message.sms",course.getName());
        }

        return add;
    }
    //下线
    @Override
    public AjaxResult offLine(List<Long> ids) {
        AjaxResult delete = AjaxResult.me();
        for (Long id: ids) {
            //查出课程
            Course course = super.selectById(id);
            //判断课程是否为上线的状态
            if (course.getStatus() == 0) {
                throw new RuntimeException("这已经是个下线状态了");
            }
            //修改数据库的状态
            course.setStatus(0);//下线
            super.updateById(course);
            //从ES里面移除
            delete = courseClient.delete(course.getId());
            if (!delete.isSuccess())
                throw new RuntimeException(delete.getMessage());
        }
        return delete;
    }

    @Override
    public AjaxResult queryCourses(CourseDocQuery query) {
        AjaxResult queryCourses = courseClient.query(query);
        return queryCourses;
    }


    //课程的基本信息和市场信息详情信息封装成CourseDoc
    private CourseDoc courseToCourseDoc(Course course) {
        CourseDoc courseDoc = new CourseDoc();
        //课程基本信息
        BeanUtils.copyProperties(course, courseDoc);
        //市场信息
        CourseMarket market = courseMarketMapper.selectById(course.getId());
        BeanUtils.copyProperties(market, courseDoc);
        //详情信息
        CourseDetail courseDetail = courseDetailMapper.selectById(course.getId());
        BeanUtils.copyProperties(courseDetail, courseDoc);
        //课程分类名称
        CourseType courseType = courseTypeMapper.selectById(course.getCourseTypeId());
        BeanUtils.copyProperties(courseType, courseDoc);

        return courseDoc;
    }

}
